package com.luo.demo.security.controller;

import com.luo.demo.sc.base.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.log.LogMessage;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 页面controller
 *
 * @author luohq
 * @version 1.0.0
 * @date 2022-02-14 14:52
 */
@Controller
@Slf4j
public class PageController {

    @GetMapping("/")
    public String index(Model model, Authentication authentication) {
        log.info("main Authentication: {}", JsonUtils.toJson(authentication));
        String welcomeMsg = "Client1 - 欢迎你 - " + authentication.getName() + "!";
        log.info("cur welcomeMsg: {}", welcomeMsg);
        model.addAttribute("welcomeMsg", welcomeMsg);
        return "/main";
    }

    @GetMapping("/front_logout")
    public void frontLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {

        log.info("front logout");
        //clear session
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
            if (log.isDebugEnabled()) {
                log.debug("Invalidated session {}", session.getId());
            }
        }

        //clear SecurityContext
        SecurityContext context = SecurityContextHolder.getContext();
        if (null != context) {
            SecurityContextHolder.clearContext();
            context.setAuthentication(null);
        }

        //resp 200
        response.setStatus(HttpStatus.OK.value());
        response.getWriter().flush();

    }

}
